package com.example.springboot.utils;

import cn.hutool.crypto.asymmetric.RSA;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Map;

public class JwtUtil {
    private static final String RSA_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDHAsO4ZNmsWAFTqA7hXjJsCGYcGay7T3kOg2VX6z0wjXgR++qFGaRPoMVUr95fL+G1VuhL/HbuRZBoIsPslpGob7o80s6+agEQv5Eurf5MXy5+PH/2UCg9SU0PnGn3yeWQr7CUHWWbp6YiG+LodpsoHfKhxP/fbwpoZiYXt70W0d9SYjysheCPAVYZ01f+E2fwr/jfzYPk6nw672B953AV4zaiy8CwWhD7cY9x3VCc4emyMffwKnk7LckVdmHu2HEVId6ickg6p2RRamUWn6aTmPdWxJT/T+Yfq1xgDTmSiPGu5KeBg7xFcne3V6gja9PISr9SbZZKIluAl2veqVQrAgMBAAECggEAPSsI3FLHIvVTxxJHLJcG2XTFacqscFAvjbnuOtU3lAZPivuKrEli2wS30l1R9KDjd5jUQpLBPWBNT+yrmrr23zYkIJDM8fLkC/FNnvLk0DWLNUrELAGcNKYklPFHEt3P/SY7GHNmqS6g3igDGN9nti9qRbWmzdaz9L285JpZeLsS2Itz1OwKLWdKjw8z28O7AIT287/cbKxNhaXLuJybzxGR8pgTz20vpwxLciHacRVjdehDjz+emRHy+ABe+6BqOFtnMnhsM8OIkoqOIvoEgS2khT4P5YFwwWd9c35CjhZefc7k13AXN5el+2LUkNo3GqAB0X/oMVBKDcGX9OZe2QKBgQD3hpYQokF5HN5gnmQpwkn4H3Q7z5hZsSFMIdJjpJbcoh8mb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dNX/hNn8K/4382D5Op8Ou9gfedwFeM2osvAsFoQ+3GPcd1QnOHpsjH38Cp5Oy3JFXZh7thxFSHeonJIOqdkUWplFp+mk5j3VsSU/0/mH6tcYA05kojxruSngYO8RXJ3t1eoI2vTyEq/Um2WSiJbgJdr3qlUKwIDAQAB";

    /**
     * 生成token
     * @param payload token携带的信息
     * @return token字符串
     */
    public static String getTokenRsa(Map<String,String> payload){
        System.out.println(payload);
        // 指定token过期时间为7天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        // 构建payload
        payload.forEach((k,v) -> builder.withClaim(k,v));

        // 利用hutool创建RSA
        RSA rsa = new RSA(RSA_PRIVATE_KEY, null);
        // 获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) rsa.getPrivateKey();
        // 签名时传入私钥
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.RSA256(null, privateKey));
        return token;
    }

    /**
     * 解析token
     * @param token token字符串
     * @return 解析后的token
     */
    public static DecodedJWT decodeRsa(String token){
        // 利用hutool创建RSA
        RSA rsa = new RSA(null, RSA_PUBLIC_KEY);
        // 获取RSA公钥
        RSAPublicKey publicKey = (RSAPublicKey) rsa.getPublicKey();
        // 验签时传入公钥
        JWTVerifier jwtVerifier = JWT.require(Algorithm.RSA256(publicKey, null)).build();

        try {
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            return decodedJWT;
        } catch (JWTVerificationException e) {
            // 捕获JWTVerificationException，并抛出TokenExpiredException
            throw new TokenExpiredException("Token has expired: " + e.getMessage());
        }
    }
    /**
     * 通过token获取id
     * @param token token字符串
     * @return 用户id
     */
    public static Integer getUserIdByToken(String token){
        // 利用hutool创建RSA
        RSA rsa = new RSA(null, RSA_PUBLIC_KEY);
        // 获取RSA公钥
        RSAPublicKey publicKey = (RSAPublicKey) rsa.getPublicKey();
        // 验签时传入公钥
        JWTVerifier jwtVerifier = JWT.require(Algorithm.RSA256(publicKey, null)).build();
        System.out.println(token);
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Integer id= Integer.parseInt(decodedJWT.getClaim("userId").asString());
        return id;
    }


}
